{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Linear Regression for Diabetes dataset（糖尿病数据集的线性回归） - Lesson 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Import needed libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from sklearn import datasets, linear_model, model_selection\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load the diabetes dataset, divided into `X` data and `y` features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "X, y = datasets.load_diabetes(return_X_y=True)\n",
    "print(X)\n",
    "print(X.shape)\n",
    "print(X[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在代码中，shape 函数的作用是返回数组的形状（即数组的维度信息）。对于 NumPy 数组或类似的结构，shape 是一个属性，它以元组的形式返回数组在每个维度上的大小。\n",
    "\n",
    "在你的代码中：\n",
    "\n",
    "```\n",
    "X, y = datasets.load_diabetes(return_X_y=True)\n",
    "print(X)\n",
    "print(X.shape)\n",
    "print(X[0])\n",
    "```\n",
    "\n",
    "X 是一个二维数组，表示糖尿病数据集的特征矩阵。\n",
    "X.shape 返回的是一个元组，表示 X 的形状。例如，(442, 10) 表示 X 有 442 行和 10 列。\n",
    "442 表示数据集中有 442 个样本。\n",
    "10 表示每个样本有 10 个特征。\n",
    "通过 shape，你可以快速了解数据的大小和维度，这在机器学习中非常重要，因为模型训练和数据预处理通常需要知道数据的形状。\n",
    "\n",
    "例如，输出可能是：\n",
    "\n",
    "这表示数据集有 442 个样本，每个样本有 10 个特征。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Select just one feature to target for this exercise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "# Selecting the 3rd feature\n",
    "X = X[:, 2]\n",
    "print(X.shape)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "\n",
    "#Reshaping to get a 2D array\n",
    "X = X.reshape(-1, 1)\n",
    "print(X.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Split the training and test data for both `X` and `y`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`model_selection.train_test_split` 是来自 Scikit-learn 的一个函数，用于将数据集拆分为训练集和测试集。它的作用是为模型训练和评估提供独立的数据集，避免模型过拟合或评估偏差。\n",
    "\n",
    "---\n",
    "\n",
    "参数解释：\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "1. **`X`**: 特征数据（输入变量），通常是一个二维数组或 DataFrame。\n",
    "2. **`y`**: 目标数据（输出变量），通常是一维数组或 Series。\n",
    "3. **`test_size=0.33`**: 指定测试集的比例，这里表示 33% 的数据将被分配为测试集，其余 67% 的数据用于训练集。\n",
    "   - 如果不指定，默认值为 `0.25`（25% 测试集）。\n",
    "   - 也可以使用 `train_size` 参数指定训练集的比例。\n",
    "4. **返回值**:\n",
    "   - `X_train`: 训练集的特征数据。\n",
    "   - `X_test`: 测试集的特征数据。\n",
    "   - `y_train`: 训练集的目标数据。\n",
    "   - `y_test`: 测试集的目标数据。\n",
    "\n",
    "---\n",
    "\n",
    "作用：\n",
    "1. **训练集 (`X_train`, `y_train`)**: 用于训练机器学习模型。\n",
    "2. **测试集 (`X_test`, `y_test`)**: 用于评估模型的性能，确保模型能够在未见过的数据上表现良好。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "---\n",
    "\n",
    "总结：  \n",
    "\n",
    "`train_test_split` 的主要作用是将数据集随机拆分为训练集和测试集，确保模型训练和评估的独立性，从而提高模型的泛化能力。\n",
    "\n",
    "Similar code found with 1 license type"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Select the model and fit it with the training data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "model = linear_model.LinearRegression()\n",
    "model.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use test data to predict a line"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "y_pred = model.predict(X_test)\n",
    "print(\"y_pred:\", y_pred)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`y_pred = model.predict(X_test)` 的作用是使用训练好的模型对测试集 `X_test` 进行预测，生成预测结果 `y_pred`。\n",
    "\n",
    "---\n",
    "\n",
    "详细解释：\n",
    "1. **`model.predict`**:\n",
    "   - 这是一个常见的机器学习模型方法，用于对输入数据进行预测。\n",
    "   - 它根据模型在训练集上的学习结果（如权重、参数等），对输入数据 `X_test` 进行推断，输出预测值。\n",
    "\n",
    "2. **`X_test`**:\n",
    "   - 测试集的特征数据，通常是一个二维数组。\n",
    "   - 模型会根据这些特征数据生成对应的预测结果。\n",
    "\n",
    "3. **`y_pred`**:\n",
    "   - 模型对 `X_test` 的预测结果。\n",
    "   - 如果是分类模型，`y_pred` 通常是预测的类别标签。\n",
    "   - 如果是回归模型，`y_pred` 通常是预测的连续数值。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "---\n",
    "\n",
    "总结：\n",
    "`model.predict(X_test)` 的作用是使用训练好的模型对测试集 `X_test` 进行预测，生成预测结果 `y_pred`，用于评估模型的性能或进行实际应用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the results in a plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "plt.scatter(X_test, y_test,  color='black')\n",
    "plt.plot(X_test, y_pred, color='blue', linewidth=3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下是代码中各个方法的作用和功能解释：\n",
    "\n",
    "---\n",
    "\n",
    "### 1. **`plt.scatter(X_test, y_test, color='black')`**\n",
    "   - **作用**: 绘制散点图。\n",
    "   - **参数**:\n",
    "     - `X_test`: 测试集的特征数据（横坐标）。\n",
    "     - `y_test`: 测试集的目标数据（纵坐标）。\n",
    "     - `color='black'`: 设置散点的颜色为黑色。\n",
    "   - **功能**: 将测试集的实际数据点绘制在图中，便于观察模型预测结果与实际数据的差异。\n",
    "\n",
    "---\n",
    "\n",
    "### 2. **`plt.plot(X_test, y_pred, color='blue', linewidth=3)`**\n",
    "   - **作用**: 绘制预测结果的曲线或直线。\n",
    "   - **参数**:\n",
    "     - `X_test`: 测试集的特征数据（横坐标）。\n",
    "     - `y_pred`: 模型对测试集的预测结果（纵坐标）。\n",
    "     - `color='blue'`: 设置线条颜色为蓝色。\n",
    "     - `linewidth=3`: 设置线条宽度为 3。\n",
    "   - **功能**: 将模型的预测结果绘制为一条蓝色的线，直观展示模型的拟合效果。\n",
    "\n",
    "---\n",
    "\n",
    "### 3. **`plt.show()`**\n",
    "   - **作用**: 显示绘制的图形。\n",
    "   - **功能**: 将前面用 `plt.scatter` 和 `plt.plot` 绘制的图形显示出来。没有这个方法，图形不会被渲染到屏幕上。\n",
    "\n",
    "---\n",
    "\n",
    "### 综合功能：\n",
    "这段代码的作用是将测试集的实际数据点（黑色散点）和模型的预测结果（蓝色线条）绘制在同一张图上，直观展示模型的拟合效果。\n",
    "\n",
    "---\n",
    "\n",
    "### 示例：\n",
    "假设我们有以下数据：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "# 示例数据\n",
    "X_test = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)\n",
    "y_test = np.array([1.2, 2.1, 3.0, 3.9, 5.1])\n",
    "y_pred = np.array([1, 2, 3, 4, 5])\n",
    "\n",
    "# 绘图\n",
    "plt.scatter(X_test, y_test, color='black')  # 绘制实际数据点\n",
    "plt.plot(X_test, y_pred, color='blue', linewidth=3)  # 绘制预测结果\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "输出图形：\n",
    "- 黑色散点表示实际数据点。\n",
    "- 蓝色直线表示模型的预测结果。\n",
    "\n",
    "---\n",
    "\n",
    "### 总结：\n",
    "- **`plt.scatter`**: 绘制实际数据点。\n",
    "- **`plt.plot`**: 绘制模型预测结果的曲线或直线。\n",
    "- **`plt.show`**: 显示图形。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  },
  "metadata": {
   "interpreter": {
    "hash": "70b38d7a306a849643e446cd70466270a13445e5987dfa1344ef2b127438fa4d"
   }
  },
  "orig_nbformat": 2
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
